<?php

    function tvn_order_update_field($oid, $values) {
        return db_update('tvn_order')->fields($values)->condition('oid', $oid)->execute();
    }

    function tvn_order_get_data($status, $header) {
        $query = db_select('tvn_order', 'o')->extend('PagerDefault')->extend('TableSort');
        $query->fields('o');
        $query->condition('o.status', $status);
        $query->limit(50);
        $query->orderByHeader($header);
        return $query->execute();
    }

    function tvn_order_get_order_by_id($oid) {
        return db_select('tvn_order', 'o')->fields('o')->condition('o.oid', $oid)->execute()->fetchObject();
    }

    function _tvn_order_get_orders_user($uid, $status) {
        $query = db_select('node', 'n');
        $query->leftJoin('field_data_field_order_parcels_added', 'p', 'p.revision_id = n.vid');
        $query->fields('n', array('nid'));
        $query->condition('n.uid', $uid);
        $query->condition('n.type', 'warehouse_order');
        if (isset($status)) {
            $query->condition('p.field_order_parcels_added_value', $status);
        }
        return $query->execute()->fetchCol();
    }

    function _tvn_order_find_shelf_for_item() {
        $sid = 0;
        $num_shelf = variable_get('item_per_shelf', 0);
        $shelfs = _tvn_order_get_all_shelf();
        foreach ($shelfs as $shelf) {
            $count = _tvn_order_count_item_in_shelf($shelf->tid);
            if ($count < $num_shelf) {
                $sid = $shelf->tid;
                break;
            }
        }
        return $sid;
    }

    function _tvn_order_get_all_shelf() {
        $list = array();
        $terms = taxonomy_get_tree(5);
        foreach ($terms as $term) {
            if ($term->depth == 2) {
                $list[$term->tid] = $term;
            }
        }
        return $list;
    }

    function _tvn_order_position_html($sid) {
        $html = '';
        $tid = !empty($sid) ? $sid : 0;
        $terms = taxonomy_get_parents_all($tid);
        if (!empty($terms)) {
            foreach (array_reverse($terms) as $term) {
                $html .= $term->name . ' > ';
            }
        }
        return $html ? substr($html, 0, -3) : 'Unknown';
    }

    function _tvn_order_count_item_in_shelf($tid) {
        $query = db_select('node', 'n');
        $query->leftJoin('field_data_field_order_position', 'op', 'n.vid = op.revision_id');
        $query->addExpression('COUNT(n.nid)', 'count');
        $query->condition('n.status', 1);
        $query->condition('n.type', 'warehouse_order');
        $query->condition('op.field_order_position_value', $tid);
        return $query->execute()->fetchField();
    }

